<template>
  <a-spin :spinning="confirmLoading">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="费用名称">
              <a-input v-model="queryFeeName" placeholder="请输入费用名称" :allowClear=true></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" icon="search" @click="querydata(queryFeeName)">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" style="margin-left: 10px" @click="add" icon="plus">新增</a-button>

      <a-button type="danger" style="margin-left: 10px" ghost @click="del" icon="delete">删除</a-button>

      <a-button type="default" style="margin-left: 10px" @click="toExamine">提交审核</a-button>
    </div>

    <!--    100-审核通过-->
    <!--    1-未提交-->
    <!--    2-审核中-->
    <!--    3-驳回-->
    <a-table
      :rowClassName="rowClassName"
      size="small"
      ref="table"
      rowKey="id"
      class="j-table-force-nowrap"
      :components="components"
      :scroll="{x:300,y:350}"
      :columns="columns2"
      :dataSource="dataSource1"
      :pagination="false"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      bordered>
      <template
        v-for="col in ['feeName', 'submitUser']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="e => handleChange(e.target.value, record.key, col)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template slot="operation" slot-scope="text, record, index">
        <div class="editable-row-operations">
        <span v-if="record.editable">
          <a @click="() => save(record.key)">保存</a>
          <a-popconfirm title="是否取消操作?" @confirm="() => cancel(record.key)">
            <a>取消</a>
          </a-popconfirm>
        </span>
          <span v-else>
          <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
        </span>
        </div>
      </template>
    </a-table>
  </a-spin>
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import '@/assets/less/TableExpand.less'
  import { httpAction, getAction, deleteAction } from '@/api/manage'
  import FeeNameDataModal from './modules/FeeNameDataModal'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'

  const columns2 = [
    {
      title: '费用名称',
      dataIndex: 'feeName',
      width: 200,
      scopedSlots: { customRender: 'feeName' }
    },
    {
      title: '提交人',
      dataIndex: 'submitUser',
      width: 100,
      align: 'center',
      scopedSlots: { customRender: 'submitUser' }
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 60,
      align: 'center',
      customRender: function(text, record) {
        if (text == 1) {
          return '未提交'
        } else if (text == 3) {
          return '被驳回'
        }
      }
    },
    {
      title: '操作',
      align: 'center',
      width: 100,
      dataIndex: 'operation',
      scopedSlots: { customRender: 'operation' }
    }
  ]
  export default {
    name: 'MineFeeNameDataList',
    mixins: [JeecgListMixin],
    components: {
      FeeNameDataModal
    },
    data() {
      this.components = {
        header: {
          cell: (h, props, children) => {
            const { key, ...restProps } = props
            const col = this.columns2.find(col => {
              const k = col.dataIndex || col.key
              return k === key
            })

            if (!col || !col.width) {
              return h('th', { ...restProps }, [...children])
            }

            const dragProps = {
              key: col.dataIndex || col.key,
              class: 'table-draggable-handle',
              attrs: {
                w: 10,
                x: col.width,
                z: 1,
                axis: 'x',
                draggable: true,
                resizable: false
              },
              on: {
                dragging: (x, y) => {
                  col.width = Math.max(x, 1)
                }
              }
            }
            const drag = h('vue-draggable-resizable', { ...dragProps })
            return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag])
          }
        }
      }
      return {
        queryFeeName: '',
        description: '费用名称数据库管理页面',
        dataSource1: [
          // {feeName:'1'}
        ],
        columns2,
        tableLoading: false,
        editingKey: '',
        confirmLoading: false,
        toolbarConfig: {
          // add 新增按钮； @remove="handleTableRemove" 删除按钮；clearSelection 清空选择按钮
          btn: ['add', 'remove']
        },
        selectedRowKeys: [],
        selectedRows: [],
        receivableList: [],
        // 表头
        columns: [
          {
            title: '费用名称',
            key: 'feeName',
            type: JVXETypes.input,
            align: 'center',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '提交人',
            key: 'submitUser',
            type: JVXETypes.input,
            align: 'center',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '状态',
            key: 'status',
            type: JVXETypes.normal,
            align: 'center',
            placeholder: '请输入${title}',
            defaultValue: ''
          }
          // {
          //
          //   title: '审核人',
          //   key: 'checkUser',
          //   type: JVXETypes.normal,
          //   align: 'center',
          //   placeholder: '请输入${title}',
          //   defaultValue: ''
          // },
          // {
          //
          //   title: '操作',
          //   type: JVXETypes.slot,
          //   width: '200px',
          //   align: 'center',
          //   slotName: 'action'
          // }
        ],
        url: {
          list: '/fee/nosubmit',
          add: '/fee/add',
          delete: '/fee/deleteBatch',
          submit: '/fee/submit',
          exportXlsUrl: '/feedata/feeNameData/exportXls',
          importExcelUrl: 'feedata/feeNameData/importExcel'

        },
        dictOptions: {}
      }
    },

    created() {
      this.querydata()
    },
    computed: {},
    methods: {
      async querydata(val) {
        var that = this
        that.tableLoading = true
        let param = {}
        param = { feeName: val ? val : '' }
        // const res = await getAction(this.url.list, param)
        // console.log(res)
        // if (res.success) {
        //   this.dataSource = res.result
        //   this.dataSource.map((item) => {
        //     item.key = item.id
        //   })
        //   console.log(this.dataSource)
        //   that.confirmLoading = false
        //   that.tableLoading = false
        //   this.$forceUpdate()
        // }
         getAction(this.url.list, param).then((res) => {
          // console.log(res)
          if (res.success) {
            let arr = res.result
            that.dataSource1 = arr.concat()
            that.dataSource1.map((data)=>{
              data.key = data.id
            })
            console.log(that.dataSource1)
            that.$forceUpdate()
            // that.$message.success(res.message)
            // that.$emit('allOk')

            // that.selectAll()
          } else {
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.confirmLoading = false
          that.tableLoading = false
        })
      },
      add() {
        this.dataSource1.push({
          key: this.dataSource1.length + 1 + '',
          feeName: '',
          submitUser: '',
          editable: true
        })
      },
      initDictConfig() {
      },
      handleValueChange(event) {
        console.log('handleValueChange.event: ', event)

      },
      // 触发单元格删除事件
      handleTableRemove(event) {

        //执行删除
        event.confirmRemove()

      },
      saveReceForm() {
        // 进行表单验证
        this.$refs.receivableTable.validateTable().then(errMap => {
          if (!errMap) {
            console.log(this.$refs.receivableTable.getTableData())
            const that = this
            this.receivableList = this.$refs.receivableTable.getTableData()
            // let formData = {
            //   costInfoList: this.receivableList,
            //   shipId: that.modelId,
            //   type: 'ys'
            // }
            console.log(this.receivableList)
            that.confirmLoading = true
            httpAction(this.url.add, this.receivableList, 'post').then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                // that.$emit('allOk')

                // that.selectAll()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          } else {
            // 验证未通过，errMap里包含具体未验证通过的详情
            this.$message.error('数据不完整')

          }
        })

      },
      // 当选择的行变化时触发的事件
      handleSelectRowChange(event) {

        this.selectedRows = event.selectedRows
        // if (this.selectedRows.length > 0) {
        //   this.isdelete = true
        // } else {
        //   this.isdelete = false
        // }
      },

      handleChange(value, key, column) {
        const newData = [...this.dataSource1]
        const target = newData.filter(item => key === item.key)[0]
        if (target) {
          target[column] = value
          this.dataSource1 = newData
        }
      },
      edit(key) {
        const newData = [...this.dataSource1]
        const target = newData.filter(item => key === item.key)[0]
        this.editingKey = key
        if (target) {
          target.editable = true
          this.dataSource1 = newData
        }
      },
      //新增保存
      save(key) {
        const newData = [...this.dataSource1]
        const target = newData.filter(item => key === item.key)[0]
        if (target.feeName == null || target.feeName.length == 0) {
          this.$message.warning('请填写费用名称')
          return
        }
        if (target.submitUser == null || target.submitUser.length == 0) {
          this.$message.warning('请填写提交人')
          return
        }
        delete target.editable
        this.dataSource1 = newData
        this.editingKey = ''
        httpAction(this.url.add, target, 'post').then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.querydata(null)
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {

        })
      },
      cancel(key) {
        const newData = [...this.dataSource1]
        const target = newData.filter(item => key === item.key)[0]
        this.editingKey = ''
        if (target) {
          delete target.editable
          this.dataSource1 = newData
        }
        this.querydata(null)
      },
      onSelectChange(selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        this.selectedRowKeys = selectedRowKeys
      },
      del() {
        if (this.selectedRowKeys.length > 0) {
          let param = {
            ids: this.selectedRowKeys.toString()
          }
          deleteAction(this.url.delete, param).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.querydata(null)
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {
          })
        } else {
          this.$message.warning('请选择要删除的数据')
        }
      },
      toExamine() {
        if (this.selectedRowKeys.length > 0) {
          let param = {
            ids: this.selectedRowKeys
          }
          httpAction(this.url.submit, param, 'post').then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.querydata(null)
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {
            // that.confirmLoading = false
          })
        } else {
          this.$message.warning('请选择数据')
        }
      },
      rowClassName(record, index) {
        // console.log(record.status)
        let className = 'light-row'
        if (record.status == 3) className = 'dark-row'
        return className
      }
    }
  }
</script>
<style>
  .editable-row-operations a {
    margin-right: 8px;
  }

  .light-row {
    background-color: #fff;
  }

  .dark-row {
    background-color: #fff1cf;
    color: red;
  }

  .ant-table {
    min-height: 350px !important;
  }

  .ant-empty-normal {
    margin: 140px 0 !important;
  }

  @import '~@assets/less/common.less';
</style>
<style lang="less">
  .resize-table-th {
    position: relative;

    .table-draggable-handle {
      transform: none !important;
      position: absolute;
      height: 100% !important;
      bottom: 0;
      left: auto !important;
      right: -5px;
      cursor: col-resize;
      touch-action: none;
    }
  }
</style>